<?php

namespace App\Controllers;

use App\Core\Request;
use App\Core\Response;
use App\Models\Student;

class StudentController
{
    public function index(): void
    {
        $page = (int) Request::get('page', 1);
        $pageSize = (int) Request::get('pageSize', 20);
        
        $filters = [
            'keyword' => Request::get('keyword'),
            'major' => Request::get('major'),
            'className' => Request::get('className'),
            'grade' => Request::get('grade'),
            'status' => Request::get('status'),
            'gender' => Request::get('gender')
        ];
        
        $result = Student::search($filters, $page, $pageSize);
        
        Response::paginate($result['list'], $result['total'], $page, $pageSize);
    }

    public function show(string $id): void
    {
        $student = Student::findById((int) $id);
        
        if (!$student) {
            Response::error('学生不存在', 404);
        }
        
        Response::success($student);
    }

    public function store(): void
    {
        $data = Request::validate([
            'student_id' => 'required',
            'name' => 'required',
            'gender' => 'required',
            'birth_date' => 'required',
            'id_card' => 'required',
            'major' => 'required',
            'class_name' => 'required',
            'grade' => 'required',
            'enrollment_date' => 'required'
        ]);
        
        // 检查学号是否已存在
        if (Student::findByStudentId($data['student_id'])) {
            Response::error('学号已存在', 400);
        }
        
        $data['status'] = $data['status'] ?? 'enrolled';
        
        $id = Student::create($data);
        
        Response::success(['id' => $id], '创建成功', 201);
    }

    public function update(string $id): void
    {
        $studentId = (int) $id;
        
        if (!Student::findById($studentId)) {
            Response::error('学生不存在', 404);
        }
        
        $data = Request::all();
        unset($data['id'], $data['created_at'], $data['updated_at']);
        
        Student::update($studentId, $data);
        
        Response::success(null, '更新成功');
    }

    public function destroy(string $id): void
    {
        $studentId = (int) $id;
        
        if (!Student::findById($studentId)) {
            Response::error('学生不存在', 404);
        }
        
        Student::delete($studentId);
        
        Response::success(null, '删除成功');
    }

    public function import(): void
    {
        $data = Request::getJsonData();
        $students = $data['students'] ?? [];
        
        if (empty($students)) {
            Response::error('没有要导入的数据', 400);
        }
        
        try {
            $count = Student::batchInsert($students);
            Response::success(['count' => $count], "成功导入 {$count} 条数据");
        } catch (\Exception $e) {
            Response::error('导入失败: ' . $e->getMessage(), 500);
        }
    }

    public function export(): void
    {
        $filters = [
            'keyword' => Request::get('keyword'),
            'major' => Request::get('major'),
            'className' => Request::get('className'),
            'grade' => Request::get('grade'),
            'status' => Request::get('status'),
            'gender' => Request::get('gender')
        ];
        
        $exportType = Request::get('type', 'basic'); // basic, detailed
        
        // 不使用分页，导出所有符合条件的数据
        $result = Student::search($filters, 1, 10000);
        $students = $result['list'];
        
        if ($exportType === 'detailed') {
            $this->generateDetailedExcel($students);
        } else {
            $this->generateExcel($students);
        }
    }
    
    private function generateExcel(array $students): void
    {
        require_once __DIR__ . '/../../vendor/autoload.php';
        
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        
        // 设置表头
        $headers = [
            'A1' => '学号',
            'B1' => '姓名',
            'C1' => '性别',
            'D1' => '出生日期',
            'E1' => '身份证号',
            'F1' => '专业',
            'G1' => '班级',
            'H1' => '年级',
            'I1' => '入学日期',
            'J1' => '联系电话',
            'K1' => '状态',
            'L1' => '创建时间'
        ];
        
        foreach ($headers as $cell => $value) {
            $sheet->setCellValue($cell, $value);
        }
        
        // 填充数据
        $row = 2;
        foreach ($students as $student) {
            $sheet->setCellValue('A' . $row, $student['student_id']);
            $sheet->setCellValue('B' . $row, $student['name']);
            $sheet->setCellValue('C' . $row, $student['gender']);
            $sheet->setCellValue('D' . $row, $student['birth_date']);
            $sheet->setCellValue('E' . $row, $student['id_card']);
            $sheet->setCellValue('F' . $row, $student['major']);
            $sheet->setCellValue('G' . $row, $student['class_name']);
            $sheet->setCellValue('H' . $row, $student['grade']);
            $sheet->setCellValue('I' . $row, $student['enrollment_date']);
            $sheet->setCellValue('J' . $row, $student['phone'] ?? '');
            $sheet->setCellValue('K' . $row, $student['status']);
            $sheet->setCellValue('L' . $row, $student['created_at']);
            $row++;
        }
        
        // 应用样式
        $this->applyExcelStyles($sheet, $row - 1);
        
        $filename = '学生信息_' . date('Y-m-d_H-i-s') . '.xlsx';
        
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }
    
    private function generateDetailedExcel(array $students): void
    {
        require_once __DIR__ . '/../../vendor/autoload.php';
        
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        
        // 删除默认工作表
        $spreadsheet->removeSheetByIndex(0);
        
        // 创建学生信息工作表
        $studentSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, '学生信息');
        $spreadsheet->addSheet($studentSheet, 0);
        $spreadsheet->setActiveSheetIndex(0);
        
        // 设置学生信息表头
        $headers = [
            'A1' => '学号', 'B1' => '姓名', 'C1' => '性别', 'D1' => '出生日期',
            'E1' => '身份证号', 'F1' => '专业', 'G1' => '班级', 'H1' => '年级',
            'I1' => '入学日期', 'J1' => '联系电话', 'K1' => '状态', 'L1' => '创建时间'
        ];
        
        foreach ($headers as $cell => $value) {
            $studentSheet->setCellValue($cell, $value);
        }
        
        // 填充学生数据
        $row = 2;
        foreach ($students as $student) {
            $studentSheet->setCellValue('A' . $row, $student['student_id']);
            $studentSheet->setCellValue('B' . $row, $student['name']);
            $studentSheet->setCellValue('C' . $row, $student['gender']);
            $studentSheet->setCellValue('D' . $row, $student['birth_date']);
            $studentSheet->setCellValue('E' . $row, $student['id_card']);
            $studentSheet->setCellValue('F' . $row, $student['major']);
            $studentSheet->setCellValue('G' . $row, $student['class_name']);
            $studentSheet->setCellValue('H' . $row, $student['grade']);
            $studentSheet->setCellValue('I' . $row, $student['enrollment_date']);
            $studentSheet->setCellValue('J' . $row, $student['phone'] ?? '');
            $studentSheet->setCellValue('K' . $row, $student['status']);
            $studentSheet->setCellValue('L' . $row, $student['created_at']);
            $row++;
        }
        
        $this->applyExcelStyles($studentSheet, $row - 1);
        
        $filename = '学生详细信息_' . date('Y-m-d_H-i-s') . '.xlsx';
        
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }
    
    private function applyExcelStyles($sheet, int $lastRow): void
    {
        // 设置表头样式
        $headerRange = 'A1:L1';
        $sheet->getStyle($headerRange)->getFont()->setBold(true);
        $sheet->getStyle($headerRange)->getFill()
            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
            ->getStartColor()->setARGB('FFE0E0E0');
        
        // 自动调整列宽
        foreach (range('A', 'L') as $col) {
            $sheet->getColumnDimension($col)->setAutoSize(true);
        }
        
        // 添加边框
        $dataRange = 'A1:L' . $lastRow;
        $sheet->getStyle($dataRange)->getBorders()->getAllBorders()
            ->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
    }

    public function getMajors(): void
    {
        $majors = Student::getMajors();
        Response::success($majors);
    }

    public function getClasses(): void
    {
        $major = Request::get('major');
        $classes = Student::getClasses($major);
        Response::success($classes);
    }
}

